package ocmd

import (
	"osiris/core/conversion"
	"osiris/errors"
	"osiris/logger"
	"osiris/p2p"
	"sync"
)

// BootstrapHandler BootStrap节点查询，拿到节点列表后会自动跟未知的节点握手
type BootstrapHandler struct{}

func (handler *BootstrapHandler) Handle(inputs []string, wg *sync.WaitGroup) error {
	errorOccured := true
	defer func() {
		if wg != nil && errorOccured {
			wg.Done()
		}
	}()

	if len(inputs) < 2 {
		return &errors.CommandInputError{
			Msg: "not enough arguments!",
		}
	}

	bsPeerID, err := conversion.StrToPeerID(inputs[1])
	if err != nil {
		logger.Error(map[string]interface{}{"[ocmd] [Handle bootstrap] str to peer.ID": err})
		return err
	}

	errorOccured = false
	p2p.OpenStream(p2p.BootstrapProtocol{}, bsPeerID, "", wg)

	return nil
}

func (hadnler *BootstrapHandler) PrintHelp() {
	logger.Println("usage: bootstrap [peer.ID.String() of a bootstrap peer]")
}
